package com.company.algo.niuke;


import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class TopKStr {
    public String[][] topKstrings (String[] strings, int k) {
        Map<String,Integer> map = new HashMap<>();
        for(String str:strings){
            map.put(str,map.getOrDefault(str,0)+1);
        }
        //利用最小堆对字典进行排序
        PriorityQueue<String> queue = new PriorityQueue<>((o1,o2)->{
            int count1 = map.get(o1);
            int count2 = map.get(o2);
            if (count1==count2) return o2.compareTo(o1);
            return count1-count2;
        });
        for(String key: map.keySet()){
            if (queue.size()>=k) queue.poll();
            queue.add(key);
        }
        String[][] res = new String[k][2];
        for(int i=k-1; i>=0; i--){
            String key = queue.poll();
            res[i] = new String[]{key,String.valueOf(map.get(key))};
        }
        return res;
    }
}
